package ufrj.safcp.tools.imageprocessing;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mathworks.toolbox.javabuilder.MWException;

import ufrj.safcp.imageprocessing.CardNumberReader;

public class MatlabCardImageProcessor implements ICardImageProcessor {
	
	private static Logger logger = LoggerFactory.getLogger(MatlabCardImageProcessor.class);

	private static MatlabCardImageProcessor instance;

	public synchronized static MatlabCardImageProcessor getInstance() {
		if (instance == null) {
			instance = new MatlabCardImageProcessor();
		}
		return instance;
	}
	
	protected CardNumberReader cardNumberReader;

	protected String pathToImage;

	protected MatlabCardImageProcessor() {
		try {
			cardNumberReader = new CardNumberReader();
		} catch (MWException e) {
			String msg = "Não foi possível instanciar o leitor de cartão do matlab";
			logger.error(msg);
			throw new IllegalStateException(msg, e);
		}
	}
	
	public void initialize(String pathToImage) {
		this.pathToImage = pathToImage;
	}
	
	public Integer readNumber(String image) throws UnredableNumberException {
		Object[] lerCodigoCartao;
		try {
			lerCodigoCartao = cardNumberReader.ler_codigo_cartao(1, this.pathToImage, image, false, false, false );
		} catch (MWException e) {
			String msg = "Erro ao ler o número cartão do cartão " + image;
			logger.error(msg);
			throw new IllegalStateException(msg, e);
		}
        String string = lerCodigoCartao[0].toString();
        try {
			return Integer.valueOf(string);
		} catch (NumberFormatException e) {
			throw new UnredableNumberException(string, e);
		}
	}

}
